<script setup>
import {ref} from "vue";
import Header from "../../components/HeaderVue.vue";
import {ArrowDown, Check, Delete, Edit, Pointer, Search, Star, StarFilled} from "@element-plus/icons-vue";
import {
  collectPractice,
  deleteOptions,
  deletePractice,
  listPractice,
  listSubject
} from "../../../api/practice/practice.js";
import {isPermission} from "../../../utils/utils.js";
import {ElMessage} from "element-plus";
import router from "../../../router/index.js";
import {insertOrUpdate} from "../../../store/state.js";
import {cancelCollectPractice, listCollectPractice} from "../../../api/user/user.js";


// 题目名称
const practiceName = ref('');
// 难度数组
const difficulties = ['简单', '中等', '困难'];

const subjects = ref([]);


// 题型数组
const types = ['单选题', '多选题', '判断题', '填空题', '简答题'];
// 题目数组
const practices = ref();
// 条件标签显示数组
const tags = ref([]);
// 发送条件
const condition = ref({});
// 当前导航下的url
const url = ref('/publicList');
// 收藏题目数组
const collectPractices = ref([]);

// 选择导航后的结果
const handleSelect = (index) => {
  url.value = index;
  handlePracticeList();
  // 这里你可以添加其他逻辑，比如导航到新的URL
  // console.log('Selected URL:', url.value);
};
// 关闭标签
const handleClose = (tag) => {
  tags.value.splice(tags.value.indexOf(tag), 1)
};
// 添加/更换标签
const displayTag = (condition, item) => {
  for (const index in tags.value) {
    // console.log(index)
    if (tags.value[index].condition === condition) {
      tags.value[index].item = item;
      return;
    }
  }
  tags.value.push({condition: condition, item: item});
};
// 添加/修改条件
const addCondition = (key, value) => {
  console.log(key, value);
  condition.value[key] = value;
  // console.log(condition.value);
  console.log(tags.value)
};

// 删除条件
const handleDeleteCondition = (tag) => {
  delete condition.value[tag.condition];
}
// 获取公共题库
const handlePracticeList = async () => {
  // 添加名称条件
  condition.value['name'] = practiceName.value;
  await listPractice(condition.value, url.value).then(res => {
    practices.value = res.data;
    handleCollectionPracticeList();
    handleListSubject();
  });
};

// 创建题目
const insertPractice = () => {
  insertOrUpdate.value = 0;
  router.push('/insertupdate');
}
// 修改题目
const updatePractice = (practiceId) => {
  event.stopPropagation();
  insertOrUpdate.value = 1;
  router.push('/insertupdate/' + practiceId);
}
// 删除题目
const handleDeletePractice = async (index, id) => {
  event.stopPropagation();
  await deletePractice(id).then(() => {
    handlePracticeList();
    if (isOption(index)) handleDeleteOptions(id);
    ElMessage.success("删除成功");
  })
}
// 查看是否是选择题
const isOption = (index) => {
  if (practices.value[index].type === 0 || practices.value[index].type === 1 || practices.value[index].type === 2) return true;
  else return false;
}

//删除选项
const handleDeleteOptions = async (id) => {
  await deleteOptions(id);
}

// 点击收藏按钮
const handleCollection = async (id) => {
  event.stopPropagation();
  await collectPractice(id).then(() => {
    handleCollectionPracticeList();
    ElMessage.success("收藏成功");
  })
}
// 点击取消收藏按钮
const handleCancelCollection = async (id) => {
  event.stopPropagation();
  await cancelCollectPractice(id).then(() => {
    handleCollectionPracticeList();
    ElMessage.success("取消收藏成功");
  })
}
// 查询该用户收藏的题目
const handleCollectionPracticeList = async () => {
  await listCollectPractice().then(res => {
    collectPractices.value = res.data;
  })
}

// 获取专业数组
const handleListSubject=async ()=>{
  await listSubject().then(res=>{
    subjects.value=res.data;

    console.log(subjects.value);
  })
}


// 直接执行
handlePracticeList();

</script>

<template>
  <el-container>
    <el-header >
      <el-affix>
        <div class="header-outer">
        <Header></Header>
        </div>
      </el-affix>
    </el-header>
    <el-main style="margin: 0 200px">
      <h2>题库</h2>
      <el-menu
          :default-active="url"
          class="el-menu-demo"
          mode="horizontal"
          style="margin-bottom: 10px"
          @select="handleSelect"
      >
        <el-menu-item index="/publicList"><span style="font-size: 15px">公共</span></el-menu-item>
        <!--老师才有这个<我创建的>-->
        <el-menu-item index="/privateList"><span style="font-size: 15px" v-if="isPermission(2)">我创建的</span>
        </el-menu-item>
      </el-menu>

      <!--创建题目，只有老师才显示-->
      <el-button type="primary" style="display: flex;float: right" @click="insertPractice()" v-if="isPermission(2)">
        创建题目
      </el-button>
      <!--筛选-->
      <div class="div-search">
        <el-dropdown trigger="click">
          <el-button type="primary" style="width: 100px;margin-right: 10px">
            专业
            <el-icon class="el-icon--right">
              <arrow-down/>
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu v-model="subjects" style="height: 300px">
              <el-dropdown-item v-for="subject in subjects" :key="subject"
                                @click="displayTag('subject',subject.name);addCondition('subject',subject.name)" >
                {{ subject.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown>
          <el-button type="primary" style="width: 100px;margin-right: 10px">
            难度
            <el-icon class="el-icon--right">
              <arrow-down/>
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu v-model="difficulties">
              <el-dropdown-item v-for=" (difficulty,index) in difficulties"
                                @click="displayTag('difficulty', difficulty);
                                addCondition('difficulty',index)"
                                :key="difficulty">
                {{ difficulty }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-dropdown>
          <el-button type="primary" style="width: 100px;margin-right: 10px">
            题型
            <el-icon class="el-icon--right">
              <arrow-down/>
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                  v-for="(type,index) in types"
                  @click="displayTag('type',type);
                  addCondition('type',index)">
                {{ type }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-input
            v-model="practiceName"
            style="width: 240px;float: right;margin-right: 10px"
            placeholder="请输入题目名称"
        >
          <template #append>
            <el-button :icon="Search" @click="handlePracticeList()"/>
          </template>
        </el-input>
      </div>
      <!--条件显示标签-->
      <el-tag
          v-for="tag in tags"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleClose(tag);handleDeleteCondition(tag)"
          style="margin-right: 10px"
      >
        <span>{{ tag.item }}</span>
      </el-tag>

      <el-divider/>
      <!--      题目显示卡片-->
      <el-row :gutter="20">
        <el-col :span="8" v-for="(practice,index) in practices" :key="practice.id">
          <el-card class="practice" shadow="hover" @click="router.push('/practice/'+practice.id)">
            <div style="display: flex; align-items: center; flex-wrap: wrap;">
              <div>{{ practice.name }}</div>
              <!--              公共导航收藏按钮-->
              <div style="margin-left: auto;">
                <!--                <el-button type="warning" :icon="Star" circle style="margin-left: auto;" v-if="url==='/publicList'" @click="handleCollection(practice.id)"/>-->
                <!--                收藏-->
                <el-icon style="margin-left: auto;"
                         v-if="url === '/publicList' && !collectPractices.includes(practice.id)"
                         @click="handleCollection(practice.id)" size="16">
                  <Star/>
                </el-icon>
                <!--                单点取消收藏-->
                <el-icon color="#e6a23c" style="margin-left: auto;"
                         v-if="url === '/publicList' && collectPractices.includes(practice.id)"
                         @click="handleCancelCollection(practice.id)" size="17">
                  <StarFilled/>
                </el-icon>

                <!--              我创建的导航删除按钮-->
                <el-button type="primary" :icon="Edit" circle v-if="url==='/privateList'"
                           @click="updatePractice(practice.id)"/>
                <el-button type="danger" :icon="Delete" circle v-if="url==='/privateList'"
                           @click="handleDeletePractice(index,practice.id)"/>
              </div>
            </div>
            <div style="display: flex; align-items: center; flex-wrap: wrap;">
              <el-tag type="primary" style="margin-right: 10px; margin-top: 4px;">
                {{ difficulties[practice.difficulty] }}
              </el-tag>
              <el-tag type="primary" style="margin-right: 10px; margin-top: 4px;">{{ types[practice.type] }}</el-tag>
              <el-tag type="primary" style="margin-right: 10px; margin-top: 4px;">
                <!--{{ subjects[practice.subject] }}-->
                {{ practice.subject }}
              </el-tag>
              <div style="display: flex; align-items: center; margin-top: 4px;margin-left: auto;">
                <el-icon style="margin-right: 4px;">
                  <Pointer/>
                </el-icon>
                <div>{{ practice.visits }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<style lang="less" scoped>
.header-outer {
  height: 100%;
  // 改变盒子背景 略灰一点
  background-color: #fff;
  // 改变外部盒子边界线便于区分
  border-bottom: 2px solid #eee;
  // 设置盒子底部阴影
  box-shadow: 0 2px 8px 0 rgba(7, 17, 27, 0.06);
}

.div-search {
  margin-bottom: 10px;
}

.practice {
  height: 100px;
  margin: 8px auto;
}
</style>